import*as e from"../../core/common/common.js";import*as t from"../../core/host/host.js";import*as o from"../../core/i18n/i18n.js";import*as r from"../../core/platform/platform.js";import*as a from"../../core/protocol_client/protocol_client.js";import*as s from"../../core/sdk/sdk.js";import*as n from"../../models/bindings/bindings.js";import*as i from"../../models/text_utils/text_utils.js";import*as d from"../../ui/components/data_grid/data_grid.js";import*as l from"../../ui/components/icon_button/icon_button.js";import*as m from"../../ui/legacy/components/source_frame/source_frame.js";import*as c from"../../ui/legacy/legacy.js";import*as g from"../../ui/lit-html/lit-html.js";import*as h from"./components/components.js";const p=new CSSStyleSheet;p.replaceSync(".protocol-monitor{--override-data-grid-sent-message-row-background-color:rgb(240 246 255)}.-theme-with-dark-background .protocol-monitor,\n:host-context(.-theme-with-dark-background) .protocol-monitor{--override-data-grid-sent-message-row-background-color:rgb(43 46 56)}.protocol-monitor .protocol-monitor-toolbar{border-bottom:1px solid var(--color-details-hairline)}.protocol-monitor .protocol-monitor-bottom-toolbar{border-top:1px solid var(--color-details-hairline)}\n/*# sourceURL=protocolMonitor.css */\n");const u={method:"Method",type:"Type",request:"Request",response:"Response",timestamp:"Timestamp",elapsedTime:"Elapsed time",target:"Target",record:"Record",clearAll:"Clear all",filter:"Filter",documentation:"Documentation",sMs:"{PH1} ms",noMessageSelected:"No message selected",save:"Save",session:"Session",sendRawCDPCommand:"Send a raw `CDP` command",sendRawCDPCommandExplanation:"Format: `'Domain.commandName'` for a command without parameters, or `'{\"command\":\"Domain.commandName\", \"parameters\": {...}}'` as a JSON object for a command with parameters. `'cmd'`/`'method'` and `'args'`/`'params'`/`'arguments'` are also supported as alternative keys for the `JSON` object.",selectTarget:"Select a target",showCDPCommandEditor:"Show CDP command editor",hideCDPCommandEditor:"Hide  CDP command editor",CDPCommandEditorShown:"CDP command editor shown",CDPCommandEditorHidden:"CDP command editor hidden"},b=o.i18n.registerUIStrings("panels/protocol_monitor/ProtocolMonitor.ts",u),w=o.i18n.getLocalizedString.bind(void 0,b),I=e=>g.html`${w(u.sMs,{PH1:String(e)})}`;let v;class T extends c.Widget.VBox{started;startTime;requestTimeForId;dataGridRowForId;infoWidget;dataGridIntegrator;filterParser;suggestionBuilder;textFilterUI;messages=[];isRecording=!1;#e=new S;#t=new y(this.#e);#o;constructor(){super(!0),this.started=!1,this.startTime=0,this.dataGridRowForId=new Map,this.requestTimeForId=new Map;const e=new c.Toolbar.Toolbar("protocol-monitor-toolbar",this.contentElement);this.contentElement.classList.add("protocol-monitor");const o=new c.Toolbar.ToolbarToggle(w(u.record),"record-start","record-stop");o.addEventListener(c.Toolbar.ToolbarButton.Events.Click,(()=>{o.setToggled(!o.toggled()),this.setRecording(o.toggled())})),o.setToggleWithRedColor(!0),e.appendToolbarItem(o),o.setToggled(!0);const r=new c.Toolbar.ToolbarButton(w(u.clearAll),"clear");r.addEventListener(c.Toolbar.ToolbarButton.Events.Click,(()=>{this.messages=[],this.dataGridIntegrator.update({...this.dataGridIntegrator.data(),rows:[]}),this.infoWidget.render(null)})),e.appendToolbarItem(r);const a=new c.Toolbar.ToolbarButton(w(u.save),"download");a.addEventListener(c.Toolbar.ToolbarButton.Events.Click,(()=>{this.saveAsFile()})),e.appendToolbarItem(a);const s=new c.SplitWidget.SplitWidget(!0,!0,"protocol-monitor-panel-split",250),n=new c.SplitWidget.SplitWidget(!0,!1,"protocol-monitor-panel-split-container",400);n.show(this.contentElement),this.infoWidget=new C,this.#t.addEventListener(f.CommandSent,(e=>{this.#r(JSON.stringify(e.data))}));const l={paddingRowsCount:100,showScrollbar:!0,columns:[{id:"type",title:w(u.type),sortable:!0,widthWeighting:1,visible:!0,hideable:!0,styles:{"text-align":"center"}},{id:"method",title:w(u.method),sortable:!1,widthWeighting:5,visible:!0,hideable:!1},{id:"request",title:w(u.request),sortable:!1,widthWeighting:5,visible:!0,hideable:!0},{id:"response",title:w(u.response),sortable:!1,widthWeighting:5,visible:!0,hideable:!0},{id:"elapsedTime",title:w(u.elapsedTime),sortable:!0,widthWeighting:2,visible:!0,hideable:!0},{id:"timestamp",title:w(u.timestamp),sortable:!0,widthWeighting:5,visible:!1,hideable:!0},{id:"target",title:w(u.target),sortable:!0,widthWeighting:5,visible:!1,hideable:!0},{id:"session",title:w(u.session),sortable:!0,widthWeighting:5,visible:!1,hideable:!0}],rows:[],contextMenus:{bodyRow:(e,o,r)=>{const a=d.DataGridUtils.getRowEntryForColumnId(r,"method"),s=d.DataGridUtils.getRowEntryForColumnId(r,"type");e.defaultSection().appendItem(w(u.filter),(()=>{const e=d.DataGridUtils.getRowEntryForColumnId(r,"method");this.textFilterUI.setValue(`method:${e.value}`,!0)})),e.defaultSection().appendItem(w(u.documentation),(()=>{if(!a.value)return;const[e,o]=String(a.value).split("."),r="sent"===s.value?"method":"event";t.InspectorFrontendHost.InspectorFrontendHostInstance.openInNewTab(`https://chromedevtools.github.io/devtools-protocol/tot/${e}#${r}-${o}`)}))}}};this.dataGridIntegrator=new d.DataGridControllerIntegrator.DataGridControllerIntegrator(l),this.dataGridIntegrator.dataGrid.addEventListener("cellfocused",(e=>{const t=e.data.row,o={request:d.DataGridUtils.getRowEntryForColumnId(t,"request"),response:d.DataGridUtils.getRowEntryForColumnId(t,"response"),type:d.DataGridUtils.getRowEntryForColumnId(t,"type").title};this.infoWidget.render(o)})),this.dataGridIntegrator.dataGrid.addEventListener("newuserfiltertext",(e=>{this.textFilterUI.setValue(e.data.filterText,!0)})),s.setMainWidget(this.dataGridIntegrator),s.setSidebarWidget(this.infoWidget),n.setMainWidget(s),n.setSidebarWidget(this.#t),n.hideSidebar(),n.enableShowModeSaving();const m=["method","request","response","type","target","session"];this.filterParser=new i.TextUtils.FilterParser(m),this.suggestionBuilder=new c.FilterSuggestionBuilder.FilterSuggestionBuilder(m),this.textFilterUI=new c.Toolbar.ToolbarInput(w(u.filter),"",1,.2,"",this.suggestionBuilder.completions.bind(this.suggestionBuilder),!0),this.textFilterUI.addEventListener(c.Toolbar.ToolbarInput.Event.TextChanged,(e=>{const t=e.data,o=this.filterParser.parse(t);this.dataGridIntegrator.update({...this.dataGridIntegrator.data(),filters:o})})),e.appendToolbarItem(this.textFilterUI);const g=new c.Toolbar.Toolbar("protocol-monitor-bottom-toolbar",this.contentElement);g.appendToolbarItem(n.createShowHideSidebarButton(w(u.showCDPCommandEditor),w(u.hideCDPCommandEditor),w(u.CDPCommandEditorShown),w(u.CDPCommandEditorHidden))),g.appendToolbarItem(this.#a()),g.appendToolbarItem(this.#s())}#a(){const e=w(u.sendRawCDPCommand),t=e,o=w(u.sendRawCDPCommandExplanation),r=new c.Toolbar.ToolbarInput(e,t,1,.2,o,this.#e.buildTextPromptCompletions,!1);return r.addEventListener(c.Toolbar.ToolbarInput.Event.EnterPressed,(()=>this.#r(r.value()))),r.addEventListener(c.Toolbar.ToolbarInput.Event.TextChanged,(()=>this.#n(r))),r}#s(){const e=new c.Toolbar.ToolbarComboBox((()=>{this.#o=e.selectedOption()?.value}),w(u.selectTarget));e.setMaxWidth(120);const t=s.TargetManager.TargetManager.instance(),o=()=>{e.removeOptions();for(const o of t.targets())e.createOption(`${o.name()} (${o.inspectedURL()})`,o.id())};return t.addEventListener(s.TargetManager.Events.AvailableTargetsChanged,o),o(),e}#r(e){const{command:t,parameters:o}=E(e),r=a.InspectorBackend.test,n=s.TargetManager.TargetManager.instance(),i=this.#o?n.targetById(this.#o):null,d=i?i.sessionId:"";r.sendRawMessage(t,o,(()=>{}),d),this.#e.addEntry(e)}#n(e){const t=e.valueWithoutSuggestion(),{command:o,parameters:r}=E(t);this.#t.setCommand(o,r)}static instance(e={forceNew:null}){const{forceNew:t}=e;return v&&!t||(v=new T),v}wasShown(){this.started||(this.registerCSSFiles([p]),this.started=!0,this.startTime=Date.now(),this.setRecording(!0))}setRecording(e){this.isRecording=e;const t=a.InspectorBackend.test;e?(t.onMessageSent=this.messageSent.bind(this),t.onMessageReceived=this.messageReceived.bind(this)):(t.onMessageSent=null,t.onMessageReceived=null)}targetToString(e){return e?e.decorateLabel(`${e.name()} ${e===s.TargetManager.TargetManager.instance().rootTarget()?"":e.id()}`):""}messageReceived(e,t){if(this.isRecording&&this.messages.push({...e,type:"recv",domain:"-"}),"id"in e&&e.id){const t=this.dataGridRowForId.get(e.id);if(!t)return;const o=this.dataGridIntegrator.data().rows.findIndex((e=>t===e)),r={...t,cells:t.cells.map((t=>{if("response"===t.columnId)return{...t,value:JSON.stringify(e.result||e.error)};if("elapsedTime"===t.columnId){const o=this.requestTimeForId.get(e.id);if(o)return{...t,value:Date.now()-o,renderer:I}}return t}))},a=[...this.dataGridIntegrator.data().rows];return a[o]=r,this.dataGridRowForId.delete(e.id),void this.dataGridIntegrator.update({...this.dataGridIntegrator.data(),rows:a})}const o=t,r=new l.Icon.Icon;r.data={iconName:"arrow-down",color:"var(--icon-request)",width:"20px",height:"20px"};const a={cells:[{columnId:"method",value:e.method,title:e.method},{columnId:"request",value:"",renderer:d.DataGridRenderers.codeBlockRenderer},{columnId:"response",value:JSON.stringify(e.params),renderer:d.DataGridRenderers.codeBlockRenderer},{columnId:"timestamp",value:Date.now()-this.startTime,renderer:I},{columnId:"elapsedTime",value:""},{columnId:"type",value:r,title:"received"},{columnId:"target",value:this.targetToString(o)},{columnId:"session",value:e.sessionId||""}],hidden:!1};this.dataGridIntegrator.update({...this.dataGridIntegrator.data(),rows:this.dataGridIntegrator.data().rows.concat([a])})}messageSent(e,t){this.isRecording&&this.messages.push({...e,type:"send"});const o=t,r=new l.Icon.Icon;r.data={iconName:"arrow-up-down",color:"var(--icon-request-response)",width:"20px",height:"20px"};const a={styles:{"--override-data-grid-row-background-color":"var(--override-data-grid-sent-message-row-background-color)"},cells:[{columnId:"method",value:e.method,title:e.method},{columnId:"request",value:JSON.stringify(e.params),renderer:d.DataGridRenderers.codeBlockRenderer},{columnId:"response",value:"(pending)",renderer:d.DataGridRenderers.codeBlockRenderer},{columnId:"timestamp",value:Date.now()-this.startTime,renderer:I},{columnId:"elapsedTime",value:"(pending)"},{columnId:"type",value:r,title:"sent"},{columnId:"target",value:this.targetToString(o)},{columnId:"session",value:e.sessionId||""}],hidden:!1};this.requestTimeForId.set(e.id,Date.now()),this.dataGridRowForId.set(e.id,a),this.dataGridIntegrator.update({...this.dataGridIntegrator.data(),rows:this.dataGridIntegrator.data().rows.concat([a])})}async saveAsFile(){const e=new Date,t="ProtocolMonitor-"+r.DateUtilities.toISO8601Compact(e)+".json",o=new n.FileUtils.FileOutputStream;await o.open(t)&&(o.write(JSON.stringify(this.messages,null,"  ")),o.close())}}class S{#i=200;#d=new Set;protocolMethods=this.buildProtocolCommands(a.InspectorBackend.inspectorBackend.agentPrototypes.values());constructor(e){void 0!==e&&(this.#i=e)}buildTextPromptCompletions=async(e,t,o)=>{if(!t&&!o&&e)return[];const r=[...this.#d].reverse();return r.push(...this.protocolMethods),r.filter((e=>e.startsWith(t))).map((e=>({text:e})))};buildProtocolCommands(e){const t=new Set;for(const o of e)for(const e of Object.keys(o.commandParameters))t.add(e);return t}addEntry(e){if(this.#d.has(e)&&this.#d.delete(e),this.#d.add(e),this.#d.size>this.#i){const e=this.#d.values().next().value;this.#d.delete(e)}}}class C extends c.Widget.VBox{tabbedPane;constructor(){super(),this.tabbedPane=new c.TabbedPane.TabbedPane,this.tabbedPane.appendTab("request",w(u.request),new c.Widget.Widget),this.tabbedPane.appendTab("response",w(u.response),new c.Widget.Widget),this.tabbedPane.show(this.contentElement),this.tabbedPane.selectTab("response"),this.render(null)}render(e){if(!e||!e.request||!e.response)return this.tabbedPane.changeTabView("request",new c.EmptyWidget.EmptyWidget(w(u.noMessageSelected))),void this.tabbedPane.changeTabView("response",new c.EmptyWidget.EmptyWidget(w(u.noMessageSelected)));const t=e&&e.type&&"sent"===e.type;this.tabbedPane.setTabEnabled("request",Boolean(t)),t||this.tabbedPane.selectTab("response");const o=JSON.parse(String(e.request.value)||"null");this.tabbedPane.changeTabView("request",m.JSONView.JSONView.createViewSync(o));const r="(pending)"===e.response.value?null:JSON.parse(String(e.response.value)||"null");this.tabbedPane.changeTabView("response",m.JSONView.JSONView.createViewSync(r))}}var f;!function(e){e.CommandSent="CommandSent"}(f||(f={}));class y extends(e.ObjectWrapper.eventMixin(c.Widget.VBox)){jsonEditor;constructor(e){super(),this.jsonEditor=new h.JSONEditor.JSONEditor,this.jsonEditor.protocolMethods=[...e.protocolMethods],this.element.append(this.jsonEditor),this.jsonEditor.addEventListener("keydown",(e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&this.dispatchEventToListeners(f.CommandSent,this.getCommand())}))}getCommand(){return{command:this.jsonEditor.getCommand(),parameters:this.jsonEditor.getParameters()}}setCommand(e,t){this.jsonEditor.parameters=t,this.jsonEditor.command=e}}function E(e){let t=null;try{t=JSON.parse(e)}catch(e){}return{command:t?t.command||t.method||t.cmd||"":e,parameters:t?.parameters||t?.params||t?.args||t?.arguments||{}}}var P=Object.freeze({__proto__:null,ProtocolMonitorImpl:T,CommandAutocompleteSuggestionProvider:S,InfoWidget:C,get Events(){return f},EditorWidget:y,parseCommandInput:E});export{P as ProtocolMonitor};
